const mongoose = require('mongoose')
const Vip = mongoose.model('vip')
const VipType = mongoose.model('vipType')
const VipCreateRecord = mongoose.model('vipCreateRecord')
const User = mongoose.model('user')
const { formatBody } = require('../tools')
const moment = require('moment')
const nanoid = require('nanoid')

module.exports = {
  /**
   * 会员卡类型列表
   */
  async listType(ctx) {
    let list = await VipType.find({}).sort({ 'createAt': -1 })
    let total = await VipType.countDocuments()
    return ctx.body = formatBody(1, 'ok', { total, list })
  },
  /**
  * 添加会员卡类型
  */
  async addType(ctx) {
    let { type, validDay, desc } = ctx.request.query
    if (!type || !validDay || !desc) {
      return ctx.body = formatBody(0, '类型，有效期，描述不可为空')
    }
    let vipType = new VipType({ type, validDay, desc })
    await vipType.save()
    return ctx.body = formatBody(1, 'ok')
  },
  /**
  * 删除会员卡类型
  */
  async deleteType(ctx) {
    let { _id } = ctx.request.query
    await VipType.deleteOne({
      _id
    })
    return ctx.body = formatBody(1, 'ok')
  },
  /**
   * 会员卡创建记录
   */
  async listCreateRecord (ctx) {
    let page = ctx.query.page || 1
    let limit = ctx.query.limit || 20
    let linkSaler = ctx.query.linkSaler || ''
    let query = linkSaler ? { linkSaler } : {}
    let list = await VipCreateRecord.find(query)
      .populate([
        {
          path: 'type',
          select: 'type validDay desc'
        },
        {
          path: 'linkSaler',
          select: 'nickname'
        }
      ])
      .sort({ 'createAt': -1 })
      .limit(+limit).skip(+limit * (+page - 1))
    let total = await VipCreateRecord.find(query).countDocuments()
    return ctx.body = formatBody(1, 'ok', { total, list })
  },
   /**
   * 删除创建记录
   */
  async deleteCreateRecord (ctx) {
    let _id = ctx.request.body._id
    await VipCreateRecord.deleteOne({ _id })
    await Vip.deleteMany({ createRecord: _id })
    return ctx.body = formatBody(1, 'ok')
  },
  /**
   * 会员卡列表
   */
  async list (ctx) {
    let page = ctx.query.page || 1
    let limit = ctx.query.limit || 20
    let cardNo = ctx.query.cardNo || ''
    let createRecord = ctx.query.createRecord || ''
    let query = {}
    if (cardNo) query.cardNo = { $regex: cardNo, $options: '$i' }
    if (createRecord) query.createRecord = createRecord
    let list = await Vip.find(query)
      .populate([
        {
          path: 'type',
          select: 'type validDay desc'
        },
        {
          path: 'linkSaler',
          select: 'nickname'
        }
      ])
      .sort({ 'createAt': -1 })
      .limit(+limit).skip(+limit * (+page - 1))
    let total = await Vip.find(query).countDocuments()
    return ctx.body = formatBody(1, 'ok', { total, list })
  },
  /**
   * 批量创建vip
   */
  async create (ctx) {
    let { typeId, linkSaler, number } = ctx.request.query
    let Arr = []
    number = number ? number : 1
    let vipCreateRecord = new VipCreateRecord({ type: typeId, linkSaler, number })
    for (let i = 0; i < number; i++) {
      let vip = new Vip({ cardNo: nanoid(), type: typeId, linkSaler, createRecord: vipCreateRecord._id })
      await vip.save()
      Arr.push(vip._id)
    }
    await vipCreateRecord.save()
    return ctx.body = formatBody(1, '创建成功', {
      list: Arr,
      record: vipCreateRecord
    })
  },
   /**
   * 批量删除vip
   */
  async delete (ctx) {
    let { ids } = ctx.request.body
    for (let i = 0; i < ids.length; i++) {
      await Vip.deleteOne({ _id: ids[i] })
    }
    return ctx.body = formatBody(1, '删除成功')
  },
  /**
   * 激活vip
   */
  async activation (ctx) {
    let { cardNo, uid } = ctx.request.body
    let vip = await Vip.findOne({ cardNo})
    let user = await User.findOne({ _id: uid })
    if (!vip) {
      return ctx.body = formatBody(0, '卡密不存在')
    } else if (!user) {
      return ctx.body = formatBody(0, '用户不存在')
    } else if (vip.activationDate) {
      return ctx.body = formatBody(0, '卡密已经被使用')
    } else {
      let vipType = await VipType.findOne({ _id: vip.type })
      let addDays = vipType.validDay
      let expireDate = moment().add(addDays, 'days').toDate()
      await User.updateOne({
        _id: uid
      }, {
        vip: vip._id
      })
      await Vip.updateOne({
        caedNo
      }, {
        expireDate,
        activationDate: new Date(),
        linkUser: uid
      })
      return ctx.body = formatBody(1, '激活成功', {
        expireDate: moment(expireDate).format('YYYY年MM月DD日 HH:mm:ss')
      })
    }
  },
  async destroy (ctx) {
    let list = await Vip.find({
      expireDate: {
        $lt: moment(new Date(), moment.ISO_8601)
      }
    })
    await Vip.deleteMany,({
      expireDate: {
        $lt: moment(new Date(), moment.ISO_8601)
      }
    })
    console.log('删除过期会员', list)
    if (ctx) return ctx.body = formatBody(1, '删除成功', list)
  }
}
